package com.shure.encrypt.utils;

import com.shure.encrypt.config.EncryptEntity;
import com.shure.encrypt.encrypt.EncryptService;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName EncryptDecryptConfigUtils
 * @Description TODO
 * @Author shure
 * @Date 2023/10/17 15:37
 * @Version 1.0
 **/
public class EncryptDecryptConfigUtils {


    /**
     * 获取配置了加密的字段
     *
     * @param objectClass
     * @return
     */
    public static Field[] getFields(Class<?> objectClass, List<EncryptEntity> entities) {
        for (EncryptEntity encrypt : entities) {
            if (encrypt.getName().getName().equals(objectClass.getName())) {
                Field[] fields = Arrays.stream(objectClass.getDeclaredFields())
                        .filter(field -> encrypt.getFields().contains(field.getName()))
                        .toArray(Field[]::new);
                return fields;
            }
        }
        return new Field[0];
    }

    /**
     * 解密配置的字段
     *
     * @param object
     * @param entities
     * @throws IllegalAccessException
     */
    public static void fieldListDecrypt(Object object, List<EncryptEntity> entities, EncryptService encryptService) throws IllegalAccessException {
        ArrayList resultList = (ArrayList) object;
        if (resultList.isEmpty() || entities.isEmpty()) {
            return;
        }
        Field[] declaredFields = getFields(resultList.get(0).getClass(), entities);
        if (ArrayUtils.isEmpty(declaredFields)) {
            return;
        }
        for (Object o : resultList) {
            EncryptDecryptUtils.decrypt(declaredFields, o, encryptService);
        }
    }

}
